from datetime import datetime
from flask import render_template, request
from run import app
from wxcloudrun.dao import delete_counterbyid, query_counterbyid, insert_counter, update_counterbyid
from wxcloudrun.model import Counters
from wxcloudrun.response import make_succ_empty_response, make_succ_response, make_err_response
import requests
import json
import pymysql

appid = 'wxab31bfc640aa65e4'
secret = '8d2131495ff246bee1c38657d8ad5be4'

@app.route('/api/wxLogin')
def wxLogin():
    code = request.headers['code']
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
    res = requests.get(url)
    if res.status_code == 200:
        res = json.loads(res.text)
        if 'errcode' in res:
            errmsg = res['errmsg'].split(',')[0]
            return errmsg, 401
        else:
            print(res)
            openid = res['openid']
            session = res['session_key']
            connection = pymysql.connect(
                host='10.22.101.174',
                port=3306,
                user='root',
                password='TYyt310611',
                database='hanming'
            )
            with connection:
                with connection.cursor() as cursor:
                    sql = 'SELECT id FROM user WHERE openid = %s'
                    cursor.execute(sql, openid)
                    result = cursor.fetchone()
                    print(result)
                    if result:
                        user_id = result[0]
                        return {'user_id':user_id,'open_id':openid}, 200
                    else:
                        return {'user_id':'unbind user','open_id':openid},200
    else:
        return 'login failed',401